package com.isoftstone.project.system.service.impl;


import com.isoftstone.project.system.mapper.SysRoleAppMapper;
import com.isoftstone.project.system.mapper.SysRoleMenuMapper;
import com.isoftstone.project.system.service.ISysRoleMenuService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SysRoleMenuService implements ISysRoleMenuService {

    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    SysRoleAppMapper sysRoleAppMapper;

    /**
     * 更新menu菜单
     * @param roleId
     * @param menuIds
     * @throws Exception
     */
    @Transactional
    public void saveRoleMenus(String roleId, String menuIds) throws Exception  {

        if (StringUtils.isEmpty(menuIds)) {
            /**
             * 如果没有选择菜单,直接删除这个菜单的对应关系。
             */
            sysRoleMenuMapper.deleteRoleMenusByRoleId(roleId);
        }else {
            sysRoleMenuMapper.deleteRoleMenusByRoleId(roleId);
            String[] split = menuIds.split(",");
            for (String s : split) {
                if( StringUtils.isNotBlank(s)){
                    sysRoleMenuMapper.saveRoleMenus(roleId,s,null);
                }
            }
            //保存完修改
            //sysRoleMenuMapper.updateRoleMenusAppId();
        }
    }

    @Transactional
    public void saveRoleAppIds(String roleId, String appIds) throws Exception  {

        if (StringUtils.isEmpty(appIds)) {
            /**
             * 如果没有选择菜单,直接删除这个菜单的对应关系。
             */
            sysRoleAppMapper.deleteRoleAppByRoleId(roleId);
        }else {
            sysRoleAppMapper.deleteRoleAppByRoleId(roleId);
            String[] split = appIds.split(",");
            for (String s : split) {
                if( StringUtils.isNotBlank(s)){
                    sysRoleAppMapper.saveRoleApp(roleId,s);
                }
            }
        }
    }

    public List<String> getMenusByRoleId(String roleId) throws Exception {
        return sysRoleMenuMapper.getMenusByRoleId(roleId);
    }

    @Override
    public void deleteRoleMenusByMenuId(String menuId) throws Exception {
        sysRoleMenuMapper.deleteRoleMenusByMenuId(menuId);
    }

    public List<String> getAppsByRoleId(String roleId) throws Exception {
        return sysRoleAppMapper.getAppsByRoleId(roleId);
    }
}
